package com.example.simple_android.Manager.impl;

import android.content.BroadcastReceiver;
import android.content.Context;

import com.example.simple_android.Manager.AbstractManager;
import com.example.simple_android.annotation.InjectionMark;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@InjectionMark(staticMethod = "getInstance")
public class BroadcastReceiverManager extends AbstractManager<Context, Map<String, BroadcastReceiver>> {

    /**
     * 此变量保存着全局唯一的BroadcastReceiverManager对象
     */
    private static BroadcastReceiverManager broadcastReceiverManager = new BroadcastReceiverManager();

    /**
     * 私有化构造方法，禁止其他类创建此类对象
     */
    private BroadcastReceiverManager() {
        map = new HashMap<>();
    }

    /**
     * 调用此方法获取此类全局唯一方法
     *
     * @return 此类全局唯一的对象
     */
    public static BroadcastReceiverManager getInstance() {
        if (broadcastReceiverManager == null) {
            broadcastReceiverManager = new BroadcastReceiverManager();
        }
        return broadcastReceiverManager;
    }

    /**
     * 调用此方法，获取指定上下文中，注册的所有BroadcastReceiver
     *
     * @param context 指定的上下文
     * @return 指定上下文中，注册的所有BroadcastReceiver，他是一个HashMap
     */
    public Map<String, BroadcastReceiver> getMap(Context context) {
        return this.map.get(context);
    }

    /**
     * 调用此方法，会将本管理者中，所有的BroadcastReceiver从指定的Context中注销掉，并且从本管理者中移出
     */
    @Override
    public void clear() {
        Set<Map.Entry<Context, Map<String, BroadcastReceiver>>> entries = map.entrySet();
        for (Map.Entry<Context, Map<String, BroadcastReceiver>> entry : entries) {
            Context context = entry.getKey();
            Map<String, BroadcastReceiver> value = entry.getValue();
            for (BroadcastReceiver broadcastReceiver : value.values()) {
                context.unregisterReceiver(broadcastReceiver);
            }
        }
        super.clear();
    }
}
